<template>
  <div :class="{'show':show}" class="header-search">
    <!-- <svg-icon class-name="search-icon" icon-class="search" @click.stop="click" /> -->
    <el-autocomplete
      ref="headerSearchSelect"
      v-model="search"
      :fetch-suggestions="querySearch"
      :placeholder="$t('搜索...')"
      :maxlength="20"
      size="small"
      prefix-icon="el-icon-search"
      class="header-search-select"
      @keyup.enter.native="searchData"
      @select="change"
    >
      <template slot-scope="{ item }">
        <div v-if="item.className === 'empty'" class="emptyP">{{ item.value }}</div>
        <div v-else class="name">{{ item.value }}</div>
      </template>
    </el-autocomplete>
  </div>
</template>

<script>
import Fuse from 'fuse.js'
import path from 'path'

export default {
  name: 'HeaderSearch',
  data() {
    return {
      search: '',
      options: [],
      searchPool: [],
      show: true,
      fuse: undefined,
      titles: ''
    }
  },
  computed: {
    routes() {
      return this.$store.getters.permission_routes
    }
  },
  watch: {
    routes() {
      this.searchPool = this.generateRoutes(this.routes)
    },
    searchPool(list) {
      this.initFuse(list)
    },
    show(value) {
      if (value) {
        document.body.addEventListener('click', this.close)
      } else {
        document.body.removeEventListener('click', this.close)
      }
    }
  },
  mounted() {
    this.searchPool = this.generateRoutes(this.routes)
  },
  methods: {
    click() {
      // this.show = !this.show
      if (this.show) {
        this.$refs.headerSearchSelect && this.$refs.headerSearchSelect.focus()
      }
    },
    close() {
      this.$refs.headerSearchSelect && this.$refs.headerSearchSelect.focus()
      this.options = []
      // this.show = false
    },
    change(val) {
      console.log(val)
      this.$router.push(val.path)
      this.search = ''
      this.options = []
      this.$nextTick(() => {
        // this.show = false
      })
    },
    initFuse(list) {
      this.fuse = new Fuse(list, {
        shouldSort: true,
        threshold: 0.4,
        location: 0,
        distance: 100,
        maxPatternLength: 32,
        minMatchCharLength: 1,
        keys: [
          {
            name: 'title',
            weight: 0.7
          },
          {
            name: 'path',
            weight: 0.3
          }
        ]
      })
    },
    // Filter out the routes that can be displayed in the sidebar
    // And generate the internationalized title
    generateRoutes(routes, basePath = '/', prefixTitle = []) {
      let res = []
      // eslint-disable-next-line
      for (const router of routes) {
        // skip hidden router
        if (router.hidden) {
          continue
        }
        const data = {
          path: path.resolve(basePath, router.path),
          title: [...prefixTitle]
        }

        if (router.meta && router.meta.title) {
          data.title = [...data.title, router.meta.title]
          if (router.redirect !== 'noRedirect' && data.path !== '' && data.path !== '/') {
            // only push the routes with title
            // special case: need to exclude parent router without redirect
            res.push(data)
          }
        }

        // recursive child routes
        if (router.children) {
          const tempRoutes = this.generateRoutes(
            router.children,
            data.path,
            data.title
          )
          if (tempRoutes.length >= 1) {
            res = [...res, ...tempRoutes]
          }
        }
      }
      return res
    },
    querySearch(query, cb) {
      if (query !== '') {
        this.$refs.headerSearchSelect.activated = true
        this.options = this.fuse.search(query)
        this.options.forEach(item => {
          this.titles = ''
          item.title.forEach(it => {
            this.titles += '>' + this.$t(it)
          })
          if (this.titles !== '') {
            item.value = this.titles.substr(1)
          }
        })
      } else {
        this.options = [{ 'value': this.$t('点击提示：跳转菜单 回车搜索：查询数据'), 'className': 'empty' }]
      }
      cb(this.options)
    },
    searchData() {
      if (this.search === '') {
        this.msgError(this.$t('请输入关键字！'))
        return
      }
      sessionStorage.setItem('keyword', this.search)
      this.$router.push({ path: '/searchData?' + new Date(), query: { keyword: this.search }})
      this.search = ''
      this.options = []
      this.$refs.headerSearchSelect.activated = false
      // this.show = false
    }
  }
}
</script>

<style lang="scss" scoped>
.header-search {
  font-size: 0 !important;
  position: relative;
  .el-input__suffix {
    right: 10px!important;
  }

  // .search-icon {
  //   cursor: pointer;
  //   font-size: 15px;
  //   vertical-align: middle;
  //   color: #333;
  //   position: absolute;
  //   top: 5px;
  //   z-index: 99;
  //   left: 0px;
  // }

  .header-search-select {
    font-size: 18px;
    transition: width 0.3s;
    width: 0;
    overflow: hidden;
    background: transparent;
    border-radius: 0;
    display: inline-block;
    vertical-align: middle;

    // /deep/ .el-input__inner {
    //   border-radius: 0;
    //   border: 0;
    //   padding-left: 10px;
    //   padding-right: 10px;
    //   box-shadow: none !important;
    //   vertical-align: middle;
    //   height: 30px !important;
    //   line-height: 30px !important;
    // }
  }

  &.show {
    .header-search-select {
      width: 170px;
      margin-left: 10px;
    }
    .search-icon {
      color: #a3b1bf !important;
      position: absolute;
      top: 10px;
      z-index: 99;
      font-size: 12px;
    }
  }
}

</style>
